package com.prb.consumer.config;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ClientContext {


    //  ip + port ==> 对应一个 netty 客户端
    public static Map<String , Client> clientMap = new ConcurrentHashMap<>();

    public static void initClientContext(Set<String> serverSet) {

        //初始化 netty 客户端
        serverSet.forEach(server ->{
            try {
                registerRpcClient(server);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("init clientMap :" + clientMap);

    }

    /**
     * 注册远程调用 客户端
     * @param server
     * @throws InterruptedException
     */
    public static void registerRpcClient(String server) throws InterruptedException {
        String ip = server.split(":")[0];
        Integer port = Integer.parseInt(server.split(":")[1]);
        registerClient(ip , port);
    }

    private static void registerClient(String ip , Integer port) throws InterruptedException {

        String clientName = ip + ":" + port;
        Client client = createClient(clientName , ip , port);
        //放入client
        clientMap.putIfAbsent(clientName , client);
    }

    public void removeClient(String clientName){

        clientMap.remove(clientName);

    }

    private static Client createClient(String clientName, String ip, Integer port) throws InterruptedException {

        //初始化客户端
        Client client = new Client(ip , port);
        client.initClient(clientName);

        return client;
    }

    public static Client allotClient(String serverName){

        //可以自己定义 负载均衡策略
        List<String> serverHosts = ServerScanLoader.serverHostMap.get(serverName);
        Random random = new Random();
        return clientMap.get(serverHosts.get(random.nextInt(serverHosts.size())));
    }

}
